package edu.sandau.b230151.b23015122.controller;

import edu.sandau.b230151.b23015122.Model.Book;
import edu.sandau.b230151.b23015122.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import edu.sandau.b230151.b23015122.repository.BookRepository;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Controller
public class BookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private BookRepository bookRepository;


    @RequestMapping("list")
    public String list(ModelMap map, @ModelAttribute Book book) {
        List<Book> bookList = new ArrayList<>();

        if (book.getId() != 0) {
            // 同时按照标题和ID查询
            List<Book> foundBook = bookRepository.findById(book.getId());
            bookList.addAll(foundBook);

        } else if (book.getTitle() != null) {
            // 只按照标题查询
            bookList.addAll(bookRepository.findByTitle(book.getTitle()));
        } else if (book.getTitle() != null && book.getId() != 0) {
            // 只按照ID查询
            bookList.addAll(bookRepository.findByTitleAndId(book.getTitle(), book.getId()));

        } else {
            // 没有提供查询条件，执行全部查询
            bookList.addAll(bookService.findAll(book));
        }

        map.put("bookList", bookList);
        return "list";

    }
    @RequestMapping("delete/{id}")
    public String delete(@PathVariable int  id){
        //System.out.println(id+" ");
        //books.remove(id);
        //bookRepository.deleteById(id);
        bookService.deleteById(Integer.parseInt(String.valueOf(id)));
        return "redirect:/list";
    }

    @RequestMapping("create")
    public String create(){
        return "create";
    }
    @RequestMapping("save")
    public String save(Book s){
        //books.put(s.getId(),s);
        //bookRepository.save(s);
        bookService.save(s);
        return "redirect:/list";
    }
    @RequestMapping("update/{id}")
    public String update(@PathVariable int id, ModelMap map){
        // Book s = books.get(id);
        Book s = bookService.getReferenceById(Integer.parseInt(String.valueOf(id)));
        map.put("book",s);
        return "update";
    }


}
